const http = require('http');
const urlModule = require('url');
const fs = require('fs');
const path = require('path');

const server = http.createServer()

server.on('request', (req, res) => {
    // 获取静态资源路径
    let url = urlModule.parse(req.url).pathname
    if (url === '/') {
        //调取静待首页资源
        //拿资源一定要是绝对路径
        //动态配置决定路径 path模块来做到
        fs.readFile(path.join(__dirname,'static/index.html'),'utf-8',(err,data) =>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else if(url == '/product.html'){
        fs.readFile(path.join(__dirname,'static/product.html'),'utf-8',(err,data) =>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else if(url == '/images/pro-1.jpg'){
        fs.readFile(path.join(__dirname,'static/images/pro-1.jpg'),'utf-8',(err,data) =>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else if(url == '/images/pro-2.jpg'){
        fs.readFile(path.join(__dirname,'static/images/pro-2.jpg'),'utf-8',(err,data) =>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })    
    }else if(url == '/css/main.css'){
        fs.readFile(path.join(__dirname,'static/css/main.css'),'utf-8',(err,data) =>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }else{
        //调取静待404资源
        fs.readFile(path.join(__dirname,'static/404.html'),'utf-8',(err,data) =>{
            if(err){
                console.log(err)
            }else{
                res.setHeader('Content-type','text/html;charset=utf-8')
                res.end(data)
            }
        })
    }
})


server.listen(3000, () => {
    console.log('listen port 3000...')
})